<template>
  <div class="container-bg">
    <h3 style="margin-bottom: 10px;">门禁密码管理</h3>
    <div
      style="display: flex; justify-content: space-between; align-items: center"
    >
      <div class="filter-container">
        <el-col :span="15">
          <el-date-picker style="width: 100%;" class="filter-item" v-model="dateTime" type="datetimerange"
            :editable="false" range-separator="~"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
            @input="$forceUpdate()" start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-col>
        <el-button
          class="filter-item m-margin-l10"
          type="primary"
          @click="onSearch"
          >查询
        </el-button>
        <el-button class="filter-item m-margin-l10" type="primary" @click="handleAddPW">添加门禁密码</el-button>
      </div>
      <div class="filter-container">
        <el-button
          icon="el-icon-delete"
          class="filter-item"
          type="danger"
          plain
          @click="delEntranceGuardPasswordBatch"
        >批量删除
        </el-button>
        <el-button
          icon="el-icon-delete"
          class="filter-item"
          type="info"
          @click="delEntranceGuardPasswordReset"
        >全部清除
        </el-button>
      </div>
    </div>

    <el-table
      :data="tableData"
      style="width: 100%; margin-top: 20px"
      :max-height="500"
      :min-height="320"
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50"></el-table-column>
      <!-- <el-table-column label="序号" type="index" width="50" prop="id">
      </el-table-column> -->
      <!-- <el-table-column label="密码ID" width="100" prop="id" v-if="false"></el-table-column> -->
      <el-table-column label="密码ID" width="100" prop="id"></el-table-column>
      <el-table-column label="密码昵称" width="100" prop="sName"/>
      <el-table-column label="密码类型" width="100" prop="iPasswordType">
        <template slot-scope="scope">
          {{ scope.row.iPasswordType == 0 ? "永久密码" : "临时密码" }}
        </template>
      </el-table-column>
      <el-table-column label="访客类型" width="100" prop="iVistorType">
        <template slot-scope="scope">
          <div v-if="scope.row.iVistorType == 0">其它</div>
          <div v-if="scope.row.iVistorType == 1">外卖</div>
          <div v-if="scope.row.iVistorType == 2">朋友</div>
          <div v-if="scope.row.iVistorType == 3">访客</div>
        </template>
      </el-table-column>
      <el-table-column
        label="临时密码有效次数"
        width="150"
        prop="iTemporayVaildCount"
      ></el-table-column>
      <el-table-column label="添加时间" prop="sAddTime"></el-table-column>
      <el-table-column label="有效开始时间" prop="sBeginTime"></el-table-column>
      <el-table-column label="有效结束时间" prop="sEndTime"></el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleEdit(scope.$index, scope.row)"
          >编辑
          </el-button
          >
          <el-popconfirm
            cancel-button-text="不用了"
            class="m-margin-l10"
            confirm-button-text="好的"
            icon="el-icon-info"
            icon-color="red"
            title="您确定删除当前门禁密码吗？"
            @confirm="handleDelete(scope.$index, scope.row)"
          >
            <el-button slot="reference" size="mini" class="light_red_btn"
            >删除
            </el-button>
          </el-popconfirm>
          <!-- <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>
    <div class="bottomBox">
      <pagination
        :limit.sync="queryform.limit"
        :page.sync="queryform.page"
        :pageSizes="[10, 20, 40]"
        :total="total"
        @pagination="changePage"
      />
    </div>

    <!-- 新增弹框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      v-if="dialogFormVisible"
    >
      <el-form :model="form" ref="elForm" :rules="dialogFormRules">
        <el-row>
          <el-col :span="11">
            <el-form-item
              label="密码昵称"
              prop="sName"
            >
              <br>
              <el-input
                v-model="form.sName"
                placeholder="请输入密码昵称"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="密码类型" :rules="[
                { required: true, message: '密码类型不能为空', trigger: 'blur' },
              ]">
              <br>
              <el-select v-model="form.iPasswordType" placeholder="请选择密码类型">
                <el-option
                  :label="item.label"
                  :value="item.value"
                  v-for="item in iPasswordTypeList"
                  :key="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="门禁密码" prop="sPassword">
              <el-input
                v-model="form.sPassword"
                placeholder="请输入门禁密码"
                autocomplete="off"
                show-password
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="访客类型" prop="iVistorType">
              <br>
              <el-select v-model="form.iVistorType"
                width="300px"
                placeholder="请选择访客类型">
                <el-option
                  :label="item.label"
                  :value="item.value"
                  v-for="item in iVistorTypeList"
                  :key="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item prop="iTemporayVaildCount" label="有效次数" v-if="form.iPasswordType != 0">
              <br>
              <el-input-number
                v-model="form.iTemporayVaildCount"
                :step="1"
                step-strictly
                :min="1"
                controls-position="right"
              />
              <br>
              <span>1-99999999 (99999999为最大次度)</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="时间" v-if="form.iPasswordType != 0" prop="time">
              <br>
              <el-date-picker
                width="100%"
                v-model="form.time"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit('elForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getEntranceGuardPasswordApi,
  editEntranceGuardPasswordApi,
  addEntranceGuardSystemControlApi,
  delEntranceGuardSystemControlApi,
  delEntranceGuardPasswordBatchApi,
  delEntranceGuardPasswordResetApi, getPassWordCheckRegx,
} from "@/api/intelligent";

export default {
  name: "MvCloudgateTerminalCloudGatePassword",
  data() {
    var checkPassword = (rule, value, callback) => {
      if (!value) {
        console.log(this.passwordObj);
        return callback(new Error('密码不能为空'));
      }
     setTimeout(()=>{
       if (!new RegExp(this.passwordObj.entranceGuardPasswordRegex).test(value)) {
         console.log('in-test')
         callback(new Error(this.passwordObj.entranceGuardPasswordErrorMessage));
       }
     },500)
    };
    return {
      dialogTitle: "添加门禁密码",
      dialogFormVisible: false,
      passwordObj: {}, // 门禁密码正则+备注信息
      queryform: {
        limit: 10,
        page: 1,
        beginTime: "",
        endTime: "",
      },
      form: {
        iPasswordType: 0,
        sPassword: "",
        iVistorType: 0,
        iTemporayVaildCount: 0,
        time: [],
        sName: "",
      },
      tableData: [],
      selectList: [],
      dateTime: [],
      total: 0,
      iPasswordTypeList: [
        {
          label: "永久密码",
          value: 0,
        },
        {
          label: "临时密码",
          value: 1,
        },
      ],
      iVistorTypeList: [
        {
          label: "其他",
          value: 0,
        },
        {
          label: "外卖",
          value: 1,
        },
        {
          label: "朋友",
          value: 2,
        },
        {
          label: "访客",
          value: 3,
        },
      ],
      dialogFormRules: {
        sName: [
          {required: true, message: '密码昵称不能为空', trigger: 'blur'},
          {max: 12, message: '密码昵称长度不能超过12位', trigger: 'blur'},
        ],
        sPassword: [
          {required: true, message: '门禁密码不能为空', trigger: 'blur'},
          {required: true, pattern: /^\d{6}$/, message: '6位数字密码', trigger: ['blur', 'change']},
        ],
        iVistorType: [
          {required: true, message: '访客类型不能为空', trigger: 'blur'},
        ],
        iTemporayVaildCount: [
          {required: true, message: '有效次数不能为空', trigger: 'blur'},
          {type: 'number', min: 1, max: 99999999, message: '有效次数范围1~99', trigger: 'blur'},
        ],
        time: [
          {required: true, message: '时间不能为空', trigger: 'blur'},
        ],
      }
    };
  },
  created() {
    this.getEntranceGuardPassword();
    this.getRegx()
  },
  mounted() {
  },

  methods: {
    changePage(val) {
      console.log(123, val);
      this.queryform.page = val.page;
      this.getEntranceGuardPassword();
    },
    getRegx() {
      getPassWordCheckRegx().then(res => {
        this.passwordObj = {...res}
      })
    },
    getEntranceGuardPassword() {
      console.log(123, this.dateTime);
      if (!this.dateTime) this.dateTime = [];
      this.queryform.beginTime = this.dateTime[0];
      this.queryform.endTime = this.dateTime[1];

      if (this.dateTime.length === 0) {
        this.queryform.beginTime = "";
        this.queryform.endTime = "";
      }
      delete this.queryform.dateTime;
      // delete this.queryform.pageNum;
      console.log(72, this.queryform);
      getEntranceGuardPasswordApi(this.queryform).then((res) => {
        // console.log(332, res);
        this.tableData = [];
        this.total = 0;
        if (res.totalCount > 0) {
          this.tableData = res.data;
          this.total = res.totalCount;
        }
      });
    },
    onSearch() {
      this.getEntranceGuardPassword();
    },
    resetForm() {
      // console.log(this.form)
      this.form.iPasswordType = 0;
      this.form.sPassword = "";
      this.form.iVistorType = 0;
      this.form.iTemporayVaildCount = 0;
      this.form.time = [];
      this.form.sName = "";
      this.dateTime = [];
    },
    handleAddPW() {
      this.dialogTitle = "添加门禁密码";
      this.resetForm();
      this.dialogFormVisible = true;
    },
    handleEdit(index, row) {
      this.dialogTitle = "修改门禁密码";
      this.dialogFormVisible = true;
      this.form.id = row.id;
      this.form.iPasswordType = row.iPasswordType;
      // this.form.sPassword = row.sPassword;
      this.form.sPassword = '';
      this.form.iVistorType = row.iVistorType;
      this.form.iTemporayVaildCount = row.iTemporayVaildCount;
      this.form.time = [row.sBeginTime, row.sEndTime];
      this.form.sName = row.sName;
    },
    handleDelete(index, row) {
      // console.log(index, row);
      this.$confirm("此操作将永久删除该门禁密码, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delEntranceGuardSystemControlApi(row.id).then((res) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getEntranceGuardPassword();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    submit(formName) {
      let self = this;
      if (this.form.iPasswordType == 0) {
        this.form.iTemporayVaildCount = 99999999;
      }
      let params = {...this.form};
      if (params.iPasswordType == 1 && params.time == null) {
        self.$message.warning("临时密码必须选择时间");
        return false;
      }
      params.sBeginTime = params.time.length > 0 ? this.form.time[0] : '';
      params.sEndTime = params.time.length > 0 ? this.form.time[1] : '';
      delete params.time;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (params.iPasswordType == 1 && (!params.sBeginTime || !params.sEndTime)) {
            this.$message.warning("临时密码必须选择时间");
            return false;
          }
          if (this.dialogTitle == "添加门禁密码") {
            addEntranceGuardSystemControlApi(params).then((res) => {
              console.log(351, res);
              this.$message.success("添加成功");
              this.dialogFormVisible = false;
              this.getEntranceGuardPassword();
            });
          } else {
            editEntranceGuardPasswordApi(params).then((res) => {
              console.log(356, res);
              this.$message.success("修改成功");
              this.dialogFormVisible = false;
              this.getEntranceGuardPassword();
            });
          }
        } else {
          // console.log("error submit!!");
          return false;
        }
      });
    },

    handleSelectionChange(value) {
      this.selectList = [];
      for (let i = 0; i < value.length; i++) {
        this.selectList.push({id: value[i].id});
      }
    },
    delEntranceGuardPasswordBatch() {
      if (!this.selectList || this.selectList.length === 0) {
        this.$message.warning("请选择删除门禁密码");
        return;
      }

      let params = {
        id: [],
      };

      this.selectList.map((item) => {
        params.id.push(item.id);
      });

      const h = this.$createElement;
      this.$msgbox({
        title: "提示",
        message: h("p", null, [
          h("span", null, `此操作将永久删除所选`),
          h("i", {style: "color: #f00"}, this.selectList.length),
          h("span", null, "个门禁密码, 是否继续?"),
        ]),
        showCancelButton: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        beforeClose: (action, instance, done) => {
          if (action === "confirm") {
            done();
          } else {
            done();
          }
        },
      }).then((action) => {
        delEntranceGuardPasswordBatchApi(params).then((res) => {
          this.$message.success("删除成功");
          this.getEntranceGuardPassword();
        });
      });
    },
    delEntranceGuardPasswordReset() {
      this.$confirm("此操作将永久删除所有门禁密码, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delEntranceGuardPasswordResetApi().then((res) => {
            this.$message.success("删除成功");
            this.getEntranceGuardPassword();
          });
        })
        .catch(() => {
        });
    },
  },
};
</script>

<style lang="scss" scoped>
  .bottomBox {
    display: flex;
    justify-content: flex-end;
  }

  .bottomBox .pagination-container {
    background: none;
  }
</style>
